using System;
using System.IO;
using System.Reactive;
using System.Reactive.Linq;

namespace Live.Refresh.Components
{
    public class DirWatcher : Watchable
    {
        public DirWatcher()
        {
            Configurable = new PathConfiguration();
        }
        private FileSystemWatcher _fileSystemWatcher;
        private IObservable<EventPattern<FileSystemEventArgs>> _observable;

        public override string Name
        {
            get { return "DirWatcher"; }
        }
        public override int Order
        {
            get
            {
                return 1;
            }
        }

        protected override void Start()
        {
            
            var config = (PathConfiguration)Configurable;
            if (_fileSystemWatcher == null)
            {
                Logger.Debug("Started");
                _fileSystemWatcher = new FileSystemWatcher
                    {
                        Path = config.Path,
                        IncludeSubdirectories = true,
                        EnableRaisingEvents = true
                    };
               _observable = Observable.FromEventPattern<FileSystemEventHandler, FileSystemEventArgs>(
               h => _fileSystemWatcher.Changed += h,
               h => _fileSystemWatcher.Changed -= h);

                _observable.Throttle(TimeSpan.FromSeconds(config.Refresh)).Select(c => c.EventArgs)
                    .Subscribe(ep =>
                    {
                        Notify.Refresh(ep.FullPath);
                        Logger.Debug(ep.FullPath);
                    });
            }
            else
            {
                Logger.Debug("enable reise events second time");
                _fileSystemWatcher.EnableRaisingEvents = true;
            }
           
        }

        public override void OnStop()
        {
            _fileSystemWatcher.EnableRaisingEvents = false;
            //_observable = null;
        }

    }
}